import { IListItem } from '@/utils/interfaces'
import { apiStore } from '@/utils/store/apiStore'
import { Button, Message } from '@arco-design/web-react'
import React, { useState } from 'react'
import ApiListSelect from '../ApiListSelect'
import { filterWithParentId } from '../parentIdHandler'

// 属性
export interface IExportProps {}

const Export: React.FC<IExportProps> = () => {
    // 数据
    const [data, setData] = useState<IListItem[]>([])
    // 数据
    const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([])

    // 确定
    const handleConfirm = async () => {
        if (!selectedRowKeys.length) {
            Message.error('请选择要导出的接口')
            return
        }
        // 导出
        const list = await apiStore.getAllList()
        const selectedList = filterWithParentId(list, selectedRowKeys)
        const exportData = {
            list: selectedList,
        }
        // 下载json文件
        const blob = new Blob([JSON.stringify(exportData)], {
            type: 'application/json',
        })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `export-${randomStr()}.json`
        a.click()
        URL.revokeObjectURL(url)
        Message.success('导出成功')
    }

    // 获取数据
    const getData = async () => {
        const list = await apiStore.getAllList()
        setData(list)
    }

    // 初始化
    useEffect(() => {
        getData()
    }, [])

    return (
        <div>
            <ApiListSelect
                selectedRowKeys={selectedRowKeys}
                onSelectedRowKeysChange={setSelectedRowKeys}
                data={data}
            />
            {/* 确定 */}
            <div className='flex justify-end mt-2'>
                <Button type='primary' onClick={handleConfirm}>
                    确定
                </Button>
            </div>
        </div>
    )
}

export default Export
